import {User} from '../types/Auth';

// 模拟用户数据存储
interface StoredUser {
  id: string;
  name: string;
  email: string;
  password: string;
  createdAt: string;
}

let users: StoredUser[] = [{
      id: '1',
      name: '示例用户',
      email: '123456@qq.com',
      password: '123456',
      createdAt: '2024-01-01T00:00:00Z'
    }];

export const loginUser = async (email: string, password: string): Promise<User> => {
// 模拟网络延迟
  await new Promise<void>(resolve => setTimeout(resolve, 1000));

  const user = users.find(u => u.email === email && u.password === password);
  
  if (!user) {
    throw new Error('邮箱或密码错误');
  }

  return {
    id: user.id,
    name: user.name,
    email: user.email,
    token: 'mock-jwt-token-' + Date.now(),
  };
};

export const registerUser = async (
  name: string, 
  email: string, 
  password: string
): Promise<User> => {
  // 模拟网络延迟
  await new Promise<void>(resolve => setTimeout(resolve, 1000));

  const existingUser = users.find(u => u.email === email);
  if (existingUser) {
    throw new Error('该邮箱已被注册');
  }

  const newUser: StoredUser = {
    id: Date.now().toString(),
    name,
    email,
    password, // 在实际项目中，密码应该加密存储
    createdAt: new Date().toISOString(),
  };

  users.push(newUser);

  return {
    id: newUser.id,
    name: newUser.name,
    email: newUser.email,
    token: 'mock-jwt-token-' + Date.now(),
  };
};